/**
 * @author rxliuli
 */
const {
    emptyAllField,
    arrayToMap,
    wait,
    compare,
    DateFormatter: {
        dateFormatter,
    },
} = rx
const app = new BaseValidateVue({
    el: '#app',
    data() {
        return {
            baseIpAddressInfo: new BaseIpAddressInfo(),
            baseHouseInfoList: [],
            ruleList: [
                new ValidateObject({
                    ruleName: 'checkIpArr',
                    validate: this.checkIpArrValidate,
                }),
            ],
        }
    },
    methods: {
        createValidateList() {
            return this.ruleList;
        },
        /**
         * 添加一个 ip 地址信息
         * @return {Promise<void>}
         */
        async addBaseIpAddressInfo() {
            this.$validator.validateAll().then(async (res) => {
                if (res) {
                    if (await ajaxOption({
                        res: baseIpAddressInfoApi.add({
                            ...this.baseIpAddressInfo,
                            assignUseTime: dateFormatter.format(this.baseIpAddressInfo.assignUseTime),
                        }),
                        danger: '添加失败',
                        success: '添加成功',
                    })) {
                        forward('/basic-data/admin_ip_seg_info')
                    }
                } else {
                    await rxPrompt.dangerMsg("输入存在错误！");
                }
            })
        },
        /**
         * 清空所有的属性
         */
        resetBaseIpAddressInfo() {
            this.baseIpAddressInfo = emptyAllField(this.baseIpAddressInfo)
        },
        /**
         * 加载所有的机房信息以供选择
         */
        async initBaseHouseInfoList() {
            this.baseHouseInfoList = await baseHouseInfoApi.selectList()
        },
        async checkIpArrValidate(endIp, args) {
            const {startIp = ''} = this.baseIpAddressInfo;
            const fn = val => val.split('.').slice(0, 3)
            return compare(fn(startIp), fn(endIp))
        },
        async checkIpLastValidate(endIp, args) {
            const {startIp = ''} = this.baseIpAddressInfo;
            const last = val => val.split('.')[3]
            return last(endIp) - last(startIp) > 0
        },
    },
    computed: {
        fieldFormatter() {
            return fieldFormatter
        },
        baseHouseInfoMap() {
            return arrayToMap(this.baseHouseInfoList, ({id}) => id, ({houseName}) => houseName)
        },
    },
    async mounted() {
        await this.initBaseHouseInfoList()
    },
})
